<template>
        <div id="map" style="position: relative;">


            <div style="position: absolute;right: 50px;top:30px;z-index:100;background-color: #ffffff;padding: 7px; border-radius: 5px">
                <span style="margin: 0px 5px;font-family:微软雅黑;font-size: 13px;color: #5f6477">报警图层</span>
                <el-switch
                    v-model="value3"
                    active-text="按月付费"
                    inactive-text="按年付费"
                    @change="flashchange">
                </el-switch>
            </div>


        </div>
</template>

<script>

    import Geolocation from 'ol/Geolocation';

    import $ from 'jquery'
    import 'ol/ol.css'
    //地图图层
    import { Map, View } from 'ol'
    import Tile from 'ol/layer/Tile'
    import XYZ from 'ol/source/XYZ'
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    import {TileJSON, Vector as VectorSource} from 'ol/source';
    //图形
    import Feature from 'ol/Feature'
    import Polygon from 'ol/geom/Polygon'
    import Point from'ol/geom/Point'
    import LineString from 'ol/geom/LineString'
    import MultiLineString from 'ol/geom/MultiLineString';
    import Circle from 'ol/geom/Circle';
    //样式
    import {Fill, Icon, Stroke, Style,RegularShape,Circle as CircleStyle ,Text} from 'ol/style'
    //交互
    import Draw from 'ol/interaction/Draw'
    import Overlay from 'ol/Overlay';
    import {addProjection, addCoordinateTransforms, transform} from 'ol/proj'
    import {getArea} from "ol/sphere"
    import Select from 'ol/interaction/Select';
    import {easeOut} from 'ol/easing'
    import {unByKey} from 'ol/Observable';
    //自定义
    import Popup from "../components/popup"
    import '../style/popup.css'
    import FlashMarker  from '../components/flash'

    export default {
        /**************************************************************数据*********************************************************************/
        data(){
            return {
                name:"地图",
                map:null,
                locationLayer:null,
                vectorLayer:null,//工程图层
                selectSingleClick:null,//选中事件
                tableData:null,
                popup:null,//弹出框
                interval:[],//闪烁间隔器
                projectfeatures:[],
                isflash:false,
                value3: false,
                value4: false
            }
        },
        /**************************************************************接收父组件数据*********************************************************************/
        props:["dt"],
        /**************************************************************组件*********************************************************************/
        components: {

        },
        /**************************************************************mounted*********************************************************************/
        mounted(){
            let that=this;
            //view
            var view=new View({
                // 设置成都为地图中心
                center: transform([110,39],"EPSG:4326","EPSG:3857"),
                zoom: 10
            });
            //var osm=new ol.layer.Tile({source: new ol.source.OSM()});
            // map
            this.map = new Map({
                layers: [
                    this.getTdtLayer("vec_w"),
                    this.getTdtLayer("cva_w"),

                ],
                view:view,
                target: 'map'
            });
            view.fit([12911016,4819851,13009008,4885740]);
/*            this.map.on('click', function(evt) {
                var coor=evt.coordinate;
                alert(coor);
                console.log(coor)
            });*/
            //////////添加数据
            var jsonSource=new VectorSource({
            });
            that.vectorLayer=new VectorLayer({
                source:jsonSource,
                enderMode:'image',
                style: function (feature) {
                    return new Style({
                        image: new Icon({
                            src:"./static/img/location.png",
                            //size:[20,20]
                            scale:0.8,
                            //rotation: Math.PI / 2
                        })
                    })

                }
            });
            that.map.addLayer(that.vectorLayer);

            //生成从minNum到maxNum的随机数
            function randomNum(minNum,maxNum){
                switch(arguments.length){
                    case 1:
                        return parseInt(Math.random()*minNum+1,10);
                        break;
                    case 2:
                        return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
                        break;
                    default:
                        return 0;
                        break;
                }
            }
            for (let i=0;i<this.dt.length;i++)
            {
                let x=randomNum(12911016,13009008);
                let y=randomNum(4819851,4885740);
                var newfeature=new Feature({
                    geometry:new Point([x,y])
                });
                newfeature.setId(this.dt[i].id);
                newfeature.set("id",this.dt[i].id);
                newfeature.set("project",this.dt[i].project);
                newfeature.set("content",this.dt[i].content);
                that.projectfeatures.push(newfeature);
                //jsonSource.addFeature(newfeature);
            }

            //闪烁图层
/*            let map_div = document.getElementById("map");
            let div = document.createElement("div");
            div.id = 'css_animation';
            div.className='css_animation';
            div.innerHTML="asdfasfdasfd";
            map_div.appendChild(div);


            var point_div = document.getElementById("css_animation");
            var point_overlay = new Overlay({//定义为全局变量
                element: point_div,
                positioning: 'center-center'
            });
            this.map.addOverlay(point_overlay);
            point_overlay.setPosition([12911016,4819851]);*/


/*            var marker = new Feature(new Point([12911016,4819851]));
            that.flash(marker, 2000);
            setInterval(function () {
                that.flash(marker, 2000);
            },1000) ;*/



            for (let i=0;i<that.projectfeatures.length;i++)
            {
                jsonSource.addFeature(that.projectfeatures[i]);

            }


             //new FlashMarker(this.map, datasets);

/*            var newfeature=new Feature({
                geometry:new Point([12971440.137022696,4864643.572639329])
            });
            newfeature.set("id","1001");
            newfeature.set("project","东坝");
            newfeature.set("content","项目描述");
            var newfeature2=new Feature({
                geometry:new Point([12951440.137022696,4854643.572639329])
            });
            newfeature2.set("id","002");
            newfeature2.set("project","五棵松");
            newfeature2.set("content","项目描述");
            jsonSource.addFeatures([newfeature,newfeature2]);*/

            //添加点击事件
            this.selectSingleClick = new Select(
                {
                    layers:function (layer) {
                        if (layer==that.vectorLayer)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            );
            that.map.addInteraction(this.selectSingleClick);

            that.popup=new Popup(that.map);
            this.selectSingleClick.on('select', function(e) {
                var features=e.target.getFeatures().getArray();
                if (features.length>0)
                {
                    let feature=features[0];
                    that.zoomAndShow(feature);
                }
/*                else
                {
                    that.popup.hide()
                }*/
            });
            window.gotoProject=function(args){
                //alert(args)
                that.$router.push("/project/"+args+"/info");
            }

            //获取位置
            //getLocation();
            function getLocation(){
                if (navigator.geolocation){
                    navigator.geolocation.getCurrentPosition(showPosition,showError);
                }else{
                    alert("浏览器不支持地理定位。");
                }
            };
            function showError(error){
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        alert("定位失败,用户拒绝请求地理定位");
                        break;
                    case error.POSITION_UNAVAILABLE:
                        alert("定位失败,位置信息是不可用");
                        break;
                    case error.TIMEOUT:
                        alert("定位失败,请求获取用户位置超时");
                        break;
                    case error.UNKNOWN_ERROR:
                        alert("定位失败,定位系统失效");
                        break;
                }
            };
            function showPosition(position){
                var lat = position.coords.latitude; //纬度
                var lag = position.coords.longitude; //经度
                console.log('纬度:'+lat+',经度:'+lag);
                view.setCenter(transform([lag,lat],"EPSG:4326","EPSG:3857"));
                var feature=new Feature({
                    geometry:new Point(transform([lag,lat],"EPSG:4326","EPSG:3857"))
                });

                let locationSource=new VectorSource();
                that.locationLayer=new VectorLayer({
                    source:locationSource,
                    style:new Style({
                        image: new CircleStyle({
                            fill: new Fill({
                                color: 'rgba( 190, 207, 80, 1.00 )'
                            }),
                            stroke: new Stroke({
                                color: 'rgba( 190, 207, 80, 1.00 )',
                                width: 1.25
                            }),
                            radius: 5
                        })
                    })
                })
                locationSource.addFeature(feature)
            }

            this.map.on('click', function(evt) {
/*                var coor=evt.coordinate;
                alert(coor);*/
                that.popup.hide()


            });

        },
        /**************************************************************计算属性*********************************************************************/
        computed: {

        },
        /**************************************************************方法*********************************************************************/
        methods: {
             initData(){
                const today = dtime().format('YYYY-MM-DD')
                Promise.all([userCount(today), orderCount(today), adminDayCount(today), getUserCount(), getOrderCount(), adminCount()])
                    .then(res => {
                        this.userCount = res[0].count;
                        this.orderCount = res[1].count;
                        this.adminCount = res[2].count;
                        this.allUserCount = res[3].count;
                        this.allOrderCount = res[4].count;
                        this.allAdminCount = res[5].count;
                    }).catch(err => {
                    console.log(err)
                })
            },
            getTdtLayer(lyr) {
                var urls=[];
                for(var i=0;i<8;i++)
                {
                    urls.push( "http://t"+i+".tianditu.com/DataServer?T=" + lyr + "&X={x}&Y={y}&L={z}&tk=07c3369864c03fb6a162ac560811db9b")
                }
                var layer = new Tile({
                    source: new XYZ({
                        urls:urls
                    })
                });
                return layer;
            },

            zoomAndShow:function(feature){
                var geometry=feature.getGeometry();
                var properties=feature.getProperties();
                if(geometry.getType()=="Point")
                {
                    this.popup.show(
                        "基本信息",
                        "ID："+properties.id+"<br>"+"项目名称："+properties.project+"<br>"+"项目描述："+properties.content+"<br>"+"<button onclick='gotoProject(\""+properties.id+"\")'>进入项目</button>",
                        geometry.getCoordinates())
                }
                this.map.getView().animate({center: geometry.getCoordinates(),duration:500});
            },

            //父组件调用事件
            childFn:function (arg) {

                 let feature= this.vectorLayer.getSource().getFeatureById(arg)
                this.zoomAndShow(feature);
                //alert(arg);
            },
            flash:function(feature, duration) {
                 var that=this;
                    var start = +new Date();
                    var listenerKey; // to remove the listener after the duration

                    function animate(event) {
                        // canvas context where the effect will be drawn
                        var vectorContext = event.vectorContext;
                        var frameState = event.frameState;

                        // create a clone of the original ol.Feature
                        // on each browser frame a new style will be applied
                        var flashGeom = feature.getGeometry().clone();
                        var elapsed = frameState.time - start;
                        var elapsedRatio = elapsed / duration;
                        // radius will be 5 at start and 30 at end.
                        var radius = easeOut(elapsedRatio) * 25 + 5;
                        var opacity = easeOut(1 - elapsedRatio);

                        // you can customize here the style
                        // like color, width
                        var style = new Style({
                            image: new CircleStyle({
                                radius: radius,
                                snapToPixel: false,
                                stroke: new Stroke({
                                    color: [244, 65, 51, opacity],
                                    width: 0.25 + opacity
                                })
                            })
                        });

                        vectorContext.setStyle(style);
                        vectorContext.drawGeometry(flashGeom);
                        if (elapsed > duration) { // stop the effect
                            unByKey(listenerKey);
                            return;
                        }
                        // tell OL3 to continue postcompose animation
                        that.map.render();
                    }

                    listenerKey = that.map.on('postcompose', animate);
            },

            flashchange:function (state) {
                let that=this;
                //that.flash(that.projectfeatures[0], 2000);
                if (!state)
                {
                    for (let i=0;i<this.interval.length;i++)
                    {
                        clearInterval(that.interval[i]);
                    }

                    this.isflash=false
                }
                else if(state)
                {
                    for (let i=0;i<that.projectfeatures.length;i++)
                    {
                        //flash(newfeature, 2000);
                        //that.flash(that.projectfeatures[i], 2000);

                        if(that.projectfeatures[i].getProperties()["id"]%2==0)
                        {
                            that.flash(that.projectfeatures[i], 2000);
                            that.map.render();
                            that.interval.push(setInterval(function () {
                                that.flash(that.projectfeatures[i], 2000);

                            },1000));
                        }
                    }
                    this.isflash=true;
                }
            },


        }
    }
</script>

<style lang="less" scoped>

    #map{
        width: 100%;
        height: 100%;
    }
    .css_animation{
        height:50px;
        width:50px;
        border-radius: 25px;
        background: rgba(255, 0, 0, 0.9);
        transform: scale(0);
        animation: myfirst 3s;
        animation-iteration-count: infinite;
    }

    @keyframes myfirst{
        to{
            transform: scale(2);
            background: rgba(0, 0, 0, 0);
        }
    }
</style>
